// 这份代码专门处理逻辑层的操作
const userDao = require('../dao/userDao');
const { createUserJwtToken, verifyJwtToken } = require('../util/server_jwt');
const powerService = require('./powerService');

const userService = {
    /*
     * 用户使用工号密码登录的方法
     */
    async loginByWorkId(workId, password) {
        // 密码加密（暂不实现，上线之后再实现）
        password = password;
        // 验证登录
        let result;
        try {
            let tmp = await userDao.loginByWorkId(workId, password);
            if (tmp.length > 0) {
                if (tmp[0].allowLogin == 'true') {
                    // 生成jwt令牌
                    let payload = {uid: tmp[0].uid, username: tmp[0].username, userType: tmp[0].userType};
                    let jwt = await createUserJwtToken(payload, {expiresIn: '20h'});     // 将 jwt令牌 的有效时间设置为 20小时
                    // let jwt = await createUserJwtToken(payload, {expiresIn: '168h'});
                    // 返回数据
                    result = {success: true, msg: "登录成功", jwt: jwt, userType: tmp[0].userType};
                } else {
                    result = {success: false, msg: "该账号已被冻结，请联系管理员", jwt: ""};
                }
            } else {
                result = {success: false, msg: "工号或密码错误", jwt: ""};
            }
        } catch (err) {
            result = {success: false, msg: "查询数据库时异常，登录失败", jwt: ""};
        }
        return result;
    }
};

module.exports = userService;